<template>
  <view class="rent-history-page">

    <!-- 内容区域 -->
    <view class="content">
      <!-- 历史订单列表 -->
      <view v-if="historyList.length > 0" class="history-list">
        <view 
          v-for="order in historyList" 
          :key="order.id" 
          class="history-item"
          @click="goToOrderDetail(order.id)"
        >
          <view class="item-header">
            <view class="device-info">
              <image 
                :src="order.device?.images?.[0] || '/static/logo.png'" 
                class="device-image"
                mode="aspectFill"
              />
              <view class="device-details">
                <text class="device-name">{{ order.device?.name || '设备名称' }}</text>
                <text class="device-model">{{ order.device?.model || '' }}</text>
                <text class="rent-period">
                  {{ formatDate(order.startDate) }} 至 {{ formatDate(order.endDate) }}
                </text>
              </view>
            </view>
            <view class="order-status">
              <text class="status-text completed">已完成</text>
              <text class="order-amount">¥{{ order.totalAmount || 0 }}</text>
            </view>
          </view>

          <view class="item-footer">
            <text class="order-time">完成时间：{{ formatDateTime(order.completedAt || order.updatedAt) }}</text>
            <view class="item-actions">
              <u-button 
                type="info" 
                size="mini"
                @click.stop="goToOrderDetail(order.id)"
              >
                查看详情
              </u-button>
              <u-button 
                v-if="order.device && !order.reviewed"
                type="warning" 
                size="mini"
                @click.stop="writeReview(order)"
              >
                写评价
              </u-button>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else-if="!loading" class="empty-state">
        <text class="empty-title">暂无租赁历史</text>
        <text class="empty-desc">您还没有完成过任何租赁订单</text>
        <u-button 
          type="primary" 
          @click="goToDeviceList"
          class="empty-button"
        >
          去租赁设备
        </u-button>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <u-loading-icon mode="circle" />
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 加载更多 -->
      <u-loadmore 
        v-if="historyList.length > 0"
        :status="loadStatus" 
        @loadmore="loadMore"
      />
    </view>
  </view>
</template>

<script>
import apiService from '@/api/index.js'

export default {
  data() {
    return {
      historyList: [],
      loading: false,
      loadStatus: 'more',
      pagination: {
        page: 1,
        pageSize: 10
      }
    }
  },

  onLoad() {
    this.loadHistoryList()
  },

  onPullDownRefresh() {
    this.refreshHistoryList()
  },

  methods: {
    async loadHistoryList() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const params = {
          page: this.pagination.page,
          limit: this.pagination.pageSize,
          status: 'COMPLETED' // 只获取已完成的订单
        }
        
        const response = await apiService.order.getOrderList(params)
        
        // 处理响应数据格式
        let orders = []
        if (response.originalData && response.originalData.items) {
          orders = response.originalData.items
        } else if (response.data && response.data.items) {
          orders = response.data.items
        } else if (response.items) {
          orders = response.items
        } else if (Array.isArray(response.data)) {
          orders = response.data
        } else if (Array.isArray(response)) {
          orders = response
        }
        
        if (this.pagination.page === 1) {
          this.historyList = orders
        } else {
          this.historyList.push(...orders)
        }
        
        // 更新加载状态
        if (orders.length < this.pagination.pageSize) {
          this.loadStatus = 'nomore'
        } else {
          this.loadStatus = 'more'
        }
        
      } catch (error) {
        console.error('加载租赁历史失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },

    async refreshHistoryList() {
      this.pagination.page = 1
      this.loadStatus = 'more'
      await this.loadHistoryList()
    },

    async loadMore() {
      if (this.loadStatus === 'nomore' || this.loading) return
      
      this.pagination.page++
      await this.loadHistoryList()
    },

    goBack() {
      uni.navigateBack()
    },

    goToOrderDetail(orderId) {
      uni.navigateTo({
        url: `/pages/orders/detail?id=${orderId}`
      })
    },

    goToDeviceList() {
      uni.switchTab({
        url: '/pages/devices/list'
      })
    },

    writeReview(order) {
      // TODO: 实现评价功能
      uni.showToast({
        title: '评价功能开发中',
        icon: 'none'
      })
    },

    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },

    formatDateTime(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${this.formatDate(dateString)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
.rent-history-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.content {
  padding: 20rpx;
}

.history-list {
  .history-item {
    background: #fff;
    border-radius: 12rpx;
    padding: 24rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

    .item-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 20rpx;

      .device-info {
        display: flex;
        flex: 1;

        .device-image {
          width: 120rpx;
          height: 120rpx;
          border-radius: 8rpx;
          margin-right: 20rpx;
        }

        .device-details {
          flex: 1;
          display: flex;
          flex-direction: column;

          .device-name {
            font-size: 32rpx;
            font-weight: 600;
            color: #333;
            margin-bottom: 8rpx;
          }

          .device-model {
            font-size: 28rpx;
            color: #666;
            margin-bottom: 8rpx;
          }

          .rent-period {
            font-size: 26rpx;
            color: #999;
          }
        }
      }

      .order-status {
        display: flex;
        flex-direction: column;
        align-items: flex-end;

        .status-text {
          font-size: 26rpx;
          padding: 6rpx 12rpx;
          border-radius: 20rpx;
          margin-bottom: 8rpx;

          &.completed {
            background-color: #f6ffed;
            color: #52c41a;
            border: 1px solid #b7eb8f;
          }
        }

        .order-amount {
          font-size: 32rpx;
          font-weight: 600;
          color: #ff4757;
        }
      }
    }

    .item-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 20rpx;
      border-top: 1rpx solid #f0f0f0;

      .order-time {
        font-size: 24rpx;
        color: #999;
      }

      .item-actions {
        display: flex;
        gap: 12rpx;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  text-align: center;

  .empty-image {
    width: 300rpx;
    height: 300rpx;
    margin-bottom: 40rpx;
    opacity: 0.6;
  }

  .empty-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #666;
    margin-bottom: 16rpx;
  }

  .empty-desc {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 60rpx;
    line-height: 1.5;
  }

  .empty-button {
    width: 300rpx;
  }
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;

  .loading-text {
    font-size: 28rpx;
    color: #999;
    margin-top: 20rpx;
  }
}
</style>
